/**
 * @description get top k number from array
 */

function getTopKNumber(arr: number[], k: number) {
  if(k < 0) {
    console.error(`param k need ${k}`);
    return;
  }

  const numberMap: Map<number, number> = new Map();

  arr.forEach((item) => {
    const hasNumber = numberMap.get(item);
    if(hasNumber){
      numberMap.set(item, hasNumber + 1);
    } else {
        numberMap.set(item, 1);
    }
  })

  const arr1 = Array.from(numberMap).sort((a,b) => b[1]-a[1]);
  return arr1.slice(0, k).map(n=>n[0])
}

const nums = [1, 2, 3, 4, 4, 3, 7, 8, 8, 8, 8];

console.log(getTopKNumber(nums, 2));
